<?php

namespace App\Api\Controllers;

use App\Api\Services\LogService;
use App\Http\Controllers\Api\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class LogController extends BaseController
{
    /**
     * @操作记录详情
     * @created 在 2021/12/2 9:32 创建
     * @updated at 2022/06/05 13:48 By Sun Wu
     * @param Request $request
     * @author: Sun Wu
     */
    public function detail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' =>'required|integer',//操作日志主键id
            'type' => [
                'required',
                Rule::In([0, 1, 2]),
            ],//操作日志类型;0:入库;1:出库;2:套餐出库;
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();

        return $this->success(
            LogService::detail($data)
        );
    }

    public function logDel(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'log_id' => 'required',
            'type' => [
                'required',
                Rule::In([0, 1, 2]),
            ],//操作日志类型;0:入库;1:出库;2:套餐出库;
        ],[
            'log_id.required' => '记录id缺失',
            'type.required' => '记录id缺失',
            'type.In' => '日志类型错误',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $logIdArr = array_filter(explode(',', $data['log_id']), function($v) {
            return $v !== '';
        });

        $condition = [];
        if($this->getMainUserId() == $this->getUserId()) {
            $condition['main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            $condition['user_id'] = ['EQ' => $this->getUserId()];
        }

        $data['main_id'] = $this->getMainUserId();

        return response()->json(
            LogService::logDel($data, $logIdArr, $condition)
        );
    }
}
